import CommonAPI from "@/api/common";
import { domain } from "@/config/qiniu-config";
import * as qiniu from "qiniu-js";
import { isJsonString } from "./StringUtils";

// 上传进度回调
type ProgressCallback = (percentage: number, file: File) => void;

// 上传成功回调
type SuccessCallback = (url: string, file: File) => void;

// 上传失败回调
type ErrorCallback = (error: string, file: File) => void;

async function uploadFile(
  file: File,
  onProgress?: ProgressCallback,
  onSuccess?: SuccessCallback,
  onError?: ErrorCallback
): Promise<() => void> {
  const newName = `${new Date().getTime()}_${file.name}`;
  // 如下生成的key值用于重命名用户上传的文件名 为了防止用户上传同一个文件 (业务需求)
  const newFile = renameFile(file, newName);

  const config = {
    tokenProvider: () => CommonAPI.qiniuToken(),
  } as qiniu.UploadConfig;

  const fileData: qiniu.FileData = { type: "file", data: newFile };

  // 创建上传任务
  const uploadTask = qiniu.createDirectUploadTask(fileData, config);

  // 上传进度
  uploadTask.onProgress = (progress: any) => {
    console.log("上传进度:", progress.total.percent, "%");

    const percentage = Math.floor(progress.total.percent);
    if (onProgress) {
      onProgress(percentage, file);
    }
  };

  // 设置完成回调函数
  uploadTask.onComplete((result) => {
    if (result && isJsonString(result)) {
      const resultObj = JSON.parse(result);
      const url = `${domain}${resultObj.key}`;
      if (onSuccess) {
        onSuccess(url, file);
      }
    } else {
      if (onError) {
        onError("上传失败 : result is not json", file);
      }
    }
  });

  // 设置错误回调函数
  uploadTask.onError((error) => {
    if (onError) {
      onError(`上传失败 : ${error}`, file);
    }
  });

  uploadTask.start();

  // 返回取消上传的方法
  return () => {
    uploadTask.cancel();
  };
}
export { uploadFile };

/** 重命名文件 */
function renameFile(file: File, newFileName: string) {
  return new File([file], newFileName, {
    type: file.type,
    lastModified: file.lastModified,
  });
}
